package com.wangjiang.exception;

import com.wangjiang.rest.ResultGenerator;
import com.wangjiang.rest.entity.Result;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@CrossOrigin
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler
    public Result processException(
            Exception e,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        e.printStackTrace();

        if(e instanceof MissingServletRequestParameterException) {
            LOGGER.error("===="+e.getMessage()+"====");
            return ResultGenerator.genFailResult(e.getMessage());
        }

        if(e instanceof NoFoundException) {
            LOGGER.error("===="+e.getMessage()+"====");
            return ResultGenerator.genNoFoundResult(e.getMessage());
        }

        if(e instanceof AuthorizationException) {
            LOGGER.error("===="+e.getMessage()+"====");
            return ResultGenerator.genUnauthorizedResult();
        }

        return ResultGenerator.genInternalErrorResult(e.getMessage());
    }
}
